package com.axcessfinancial.quartz;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.axcessfinancial.ws.CustomerRegistration;

public class JobMonitorWS extends QuartzJobBean {

	private static Logger logger = Logger.getLogger(JobMonitorWS.class);

	private CustomerRegistration customer1;
	private CustomerRegistration customer2;
	private CustomerRegistration customer3;

	private MailSender mailSender;

	public void setCustomer1(CustomerRegistration customer1) {
		this.customer1 = customer1;
	}

	public void setCustomer2(CustomerRegistration customer2) {
		this.customer2 = customer2;
	}

	public void setCustomer3(CustomerRegistration customer3) {
		this.customer3 = customer3;
	}

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {

		String echo = "";

		echo = queryEcho(customer1, "st3tst01");
		logger.info(echo);
		
		echo = queryEcho(customer2, "st3tst02");
		logger.info(echo);
		
		echo = queryEcho(customer3, "st3tst03");		
		logger.info(echo);

	}

	private String queryEcho(CustomerRegistration cr, String server) {
		StringBuilder message = new StringBuilder();
		try {
			return cr.echo(server);
		} catch (RemoteAccessException rae) {
			message.append("Server ");
			message.append(server);
			message.append(" is down.");			
			logger.warn(message.toString());
			sendMail(server);
		}
		return message.toString();
	}

	private void sendMail(String server) {
		StringBuilder subject = new StringBuilder();
		subject.append("Restart server ");
		subject.append(server);
		
		SimpleMailMessage message = new SimpleMailMessage();

		message.setFrom("emelendez@axcess-financial.com");
		message.setCc(new String[]{"carias@axcess-financial.com","rsalinas@axcess-financial.com"});
		// message.setTo("DL_Stars3_Peru@axcess-financial.com");
		message.setTo("emelendez@axcess-financial.com");
		
		message.setSubject(subject.toString());
		message.setText("Test");
		mailSender.send(message);
	}

}